package com.ruoyi.application.service.impl;

import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.application.mapper.TbMatchmakerApplicationMapper;
import com.ruoyi.application.domain.TbMatchmakerApplication;
import com.ruoyi.application.service.ITbMatchmakerApplicationService;
import com.ruoyi.matchmaker.domain.TbMatchmaker;
import com.ruoyi.user.domain.TbUser;
import com.ruoyi.user.mapper.TbUserMapper;
import com.ruoyi.common.utils.StringUtils;

/**
 * 红娘服务申请Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class TbMatchmakerApplicationServiceImpl implements ITbMatchmakerApplicationService 
{
    @Autowired
    private TbMatchmakerApplicationMapper tbMatchmakerApplicationMapper;

    @Autowired
    private TbUserMapper tbUserMapper;

    /**
     * 查询红娘服务申请
     * 
     * @param applicationId 红娘服务申请主键
     * @return 红娘服务申请
     */
    @Override
    public TbMatchmakerApplication selectTbMatchmakerApplicationByApplicationId(Long applicationId)
    {
        return tbMatchmakerApplicationMapper.selectTbMatchmakerApplicationByApplicationId(applicationId);
    }

    /**
     * 查询红娘服务申请列表
     * 
     * @param tbMatchmakerApplication 红娘服务申请
     * @return 红娘服务申请
     */
    @Override
    public List<TbMatchmakerApplication> selectTbMatchmakerApplicationList(TbMatchmakerApplication tbMatchmakerApplication)
    {
        return tbMatchmakerApplicationMapper.selectTbMatchmakerApplicationList(tbMatchmakerApplication);
    }



    /**
     * 审核红娘服务申请
     *
     * @param applicationId 申请ID
     * @param status 审核状态：1-通过，2-拒绝
     * @param rejectReason 拒绝原因（拒绝时必填）
     * @param reviewerId 审核人ID
     * @return 结果
     */
    @Override
    @Transactional
    public int reviewApplication(Long applicationId, Integer status, String rejectReason, Long reviewerId)
    {
        // 查询申请信息
        TbMatchmakerApplication application = tbMatchmakerApplicationMapper.selectTbMatchmakerApplicationByApplicationId(applicationId);
        if (application == null) {
            return 0;
        }

        // 更新申请状态
        application.setApplicationStatus(status);
        application.setReviewerId(reviewerId);
        application.setReviewTime(new Date());
        application.setUpdatedAt(new Date());

        if (status == 2 && StringUtils.isNotEmpty(rejectReason)) {
            application.setRejectReason(rejectReason);
        }

        int result = tbMatchmakerApplicationMapper.updateTbMatchmakerApplication(application);

        // 如果审核通过，创建红娘信息并设置用户角色
        if (status == 1 && result > 0) {
            createMatchmakerFromApplication(application);
            updateUserRoleToMatchmaker(application.getUserId());
        }

        return result;
    }

    /**
     * 根据申请信息创建红娘信息
     *
     * @param application 申请信息
     */
    private void createMatchmakerFromApplication(TbMatchmakerApplication application) {
        TbMatchmaker matchmaker = new TbMatchmaker();
        matchmaker.setUserId(application.getUserId());
        matchmaker.setRealName(application.getRealName());
        matchmaker.setIdCardNo(application.getIdCardNo());
        matchmaker.setPhone(application.getPhone());
        matchmaker.setServiceArea(application.getServiceArea());
        matchmaker.setIntroduction(application.getIntroduction());

        // 设置资质证明（身份证正面和反面照片）
        String certification = buildCertificationFromIdCards(application.getIdCardFront(), application.getIdCardBack());
        matchmaker.setCertification(certification);

        // 设置默认值
        matchmaker.setMatchmakerLevel(1); // 预备红娘
        matchmaker.setServiceYears(0L); // 从业年限默认0
        matchmaker.setSuccessCount(0L); // 成功牵线次数默认0
        matchmaker.setMatchmakerStatus(1); // 正常状态

        Date now = new Date();
        matchmaker.setCreatedAt(now);
        // 创建时不设置updatedAt，只有修改时才设置

        // 批量插入红娘信息
        List<TbMatchmaker> matchmakerList = new ArrayList<>();
        matchmakerList.add(matchmaker);
        tbUserMapper.batchTbMatchmaker(matchmakerList);
    }

    /**
     * 构建资质证明信息（将身份证正面和反面照片组合）
     *
     * @param idCardFront 身份证正面照片URL
     * @param idCardBack 身份证反面照片URL
     * @return 资质证明信息（逗号分隔的URL字符串，与前端解析逻辑兼容）
     */
    private String buildCertificationFromIdCards(String idCardFront, String idCardBack) {
        if (StringUtils.isEmpty(idCardFront) && StringUtils.isEmpty(idCardBack)) {
            return null;
        }

        // 构建逗号分隔的URL字符串，与前端getCertificationImages方法兼容
        StringBuilder certification = new StringBuilder();

        if (StringUtils.isNotEmpty(idCardFront)) {
            certification.append(idCardFront);
        }

        if (StringUtils.isNotEmpty(idCardBack)) {
            if (certification.length() > 0) {
                certification.append(",");
            }
            certification.append(idCardBack);
        }

        return certification.toString();
    }

    /**
     * 更新用户角色为红娘
     *
     * @param userId 用户ID
     */
    private void updateUserRoleToMatchmaker(Long userId) {
        try {
            // 查询用户信息
            TbUser user = tbUserMapper.selectTbUserByUserId(userId);
            if (user != null) {
                Integer oldRole = user.getUserRole();

                // 设置用户角色为红娘(2)，如果已经是VIP则保持VIP状态但角色设为红娘
                user.setUserRole(2); // 红娘角色码是2

                // 设置修改时间
                user.setUpdatedAt(new Date());
                int result = tbUserMapper.updateTbUser(user);

                // 记录日志
                System.out.println("用户角色更新成功 - 用户ID: " + userId +
                                 ", 原角色: " + oldRole +
                                 ", 新角色: " + user.getUserRole() +
                                 ", 更新结果: " + result +
                                 ", 更新时间: " + user.getUpdatedAt());
            } else {
                System.out.println("用户角色更新失败 - 用户不存在, 用户ID: " + userId);
            }
        } catch (Exception e) {
            System.out.println("用户角色更新异常 - 用户ID: " + userId + ", 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 删除红娘服务申请信息
     *
     * @param applicationId 红娘服务申请主键
     * @return 结果
     */
    @Override
    public int deleteTbMatchmakerApplicationByApplicationId(Long applicationId)
    {
        return tbMatchmakerApplicationMapper.deleteTbMatchmakerApplicationByApplicationId(applicationId);
    }
}
